<template>
  <div>
    <div class="list-table mb20">
      <div class="area-header">
        <span class="area-header-title">{{ $t('收益统计') }}</span>
      </div>
      <el-form ref="queryForm" :model="queryParams" :inline="true">
        <!--<el-form-item label="回款项目" prop="dealId">
          <el-select v-model="queryParams.dealId" clearable placeholder="请选择回款项目">
            <el-option
              v-for="(item,index) in dealBaseList"
              :key="index"
              :label="item.dealName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>-->
        <el-form-item :label="$t('收益是否已经分配给出资人')" prop="distributionLP">
          <el-select v-model="queryParams.distributionLP" clearable :placeholder="$t('收益是否已经分配给出资人')">
            <el-option
              v-for="(dict, index) in lpOptions"
              :key="index"
              :value="dict.dictValue"
              :label="$t(dict.dictLabel)"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('收益类型')" prop="typeFee">
          <el-select v-model="queryParams.typeFee" clearable :placeholder="$t('收益类型')">
            <el-option
              v-for="(dict, index) in typeFeeOptions"
              :key="index"
              :value="dict.dictValue"
              :label="$t(dict.dictLabel)"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('回款时间')" prop="distributionTime">
          <DatePicker
            v-model="distributionDates"
            type="daterange"
          />

        </el-form-item>
        <el-form-item :label="$t('权益变更时间')" prop="distributionTime">
          <DatePicker
            v-model="equityChangeTimes"
            type="daterange"
          />

        </el-form-item>
        <el-form-item :label="$t('出资人')" prop="investId">
          <fund-lp-select v-model="queryParams.investId" :fund-id="$route.query.id" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-row type="flex">
          <el-col :span="8">
            <div id="table" v-loading="lLoading" class="table">
              <el-row>
                <div style="">
                  <el-col v-for="(statistical,index) in dataList" :key="index" :span="12">
                    <template v-for="(value,key) in statistical">
                      <div v-if="key !== 'dictValue'" :key="key" class="fund-parent mb10" style="display: flex;align-items: center;">
                        <div class="left-text">
                          <div class="chart" style="width: 2vh;display: inline-block;">
                            <circle-chart style="display: inline-block;vertical-align: middle" :expense="[expenseSum,key === 'SUM' ? -1 : value]" />
                          </div>
                          <div class="referenceSpan" :title="key === 'SUM' ? '合计' : selectDictLabel(typeFeeOptions,key)">{{ key === 'SUM' ? '合计' : selectDictLabel(typeFeeOptions,key) }}</div>
                        </div>
                        <div class="money-text" :title="value ? moneyFormat(value) : ''">{{ value ? moneyFormat(value) : '-' }}</div>
                      </div>
                    </template>
                  </el-col>
                </div>
              </el-row>
            </div>
          </el-col>
          <el-col :span="16">
            <div class="btn">
              <div class="chartBtn">
                <el-radio-group v-model="tableType" size="mini" class="mb5" @input="radioChange">
                  <el-radio-button label="hk">回款时间</el-radio-button>
                  <el-radio-button label="qybg">权益变更时间</el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <el-table
              v-loading="tLoading"
              :data="dataChartList.data"
              :cell-style="tableStyle"
              :max-height="tableHeight"
              border
            >
              <el-table-column
                v-for="(col, index) in dataChartList.columns"
                :key="index"
                :label="col.label"
                align="center"
                :show-overflow-tooltip="true"
                :prop="col.prop"
                :min-width="col.prop === 'type' ? 100 : 120"
                :fixed="col.prop === 'type' ? 'left' : col.prop === 'sum' ? 'right' : false"
              >
                <template slot-scope="scope">
                  <span v-if="col.prop === 'type'" :style="{'font-weight': scope.row[col.prop] === '合计' ? 'bolder' : ''}">{{ scope.row[col.prop] === '合计' ? scope.row[col.prop] : selectDictLabel(typeFeeOptions,scope.row[col.prop]) }}</span>
                  <span v-else class="money-text" :style="{'font-weight': scope.row['type'] === '合计' ? 'bolder' : ''}">{{ moneyFormat(scope.row[col.prop]) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="list-table">
      <div>
        <div class="area-header">
          <span class="area-header-title">{{ $t('收益明细') }}</span>
        </div>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['fund:income:edit']"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addHandle"
            >{{ $t("新增非项目收益") }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['fund:income:export']"
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="exportHandle"
            >{{ $t("导出") }}</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="fundIncomeList" :show-summary="true" :summary-method="getSummaries" border>
          <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
            <template slot-scope="scope">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('回款来源')" align="center" prop="dealName" width="150" />
          <el-table-column :label="$t('权益变更时间')" align="center" prop="equityChangeTime" width="120">
            <template slot-scope="scope">
              <el-link type="primary" @click="updateHandle(scope.row)"><span>{{ parseTime(scope.row.equityChangeTime || scope.row.distributionDate) }}</span></el-link>
            </template>
          </el-table-column>
          <el-table-column :label="$t('费用类型')" align="center" prop="typeFee" width="120" :formatter="typeFeeFormat">
            <template slot-scope="scope">
              <span v-if="scope.row.dealName">{{ '项目收益' }}</span>
              <span v-else>{{ typeFeeFormat(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('本金') + $t('金额单位')" header-align="center" align="right" prop="amountPrincipal" width="110">
            <template slot-scope="scope">
              <span class="money-text">{{ moneyFormats(scope.row.amountPrincipal, 'w') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('收益') + $t('金额单位')" header-align="center" align="right" prop="amountIncome" width="110">
            <template slot-scope="scope">
              <span class="money-text">{{ moneyFormats(scope.row.amountIncome, 'w') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('分红') + $t('金额单位')" header-align="center" align="right" prop="amountBonus" width="110">
            <template slot-scope="scope">
              <span class="money-text">{{ moneyFormats(scope.row.amountBonus, 'w') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('其它') + $t('金额单位')" header-align="center" align="right" prop="amountOthers" width="110">
            <template slot-scope="scope">
              <span class="money-text">{{ moneyFormats(scope.row.amountOthers, 'w') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('回款总额') + $t('金额单位')" header-align="center" align="right" prop="amountDistribution" width="110">
            <template slot-scope="scope">
              <span class="money-text">{{ moneyFormats(scope.row.amountDistribution, 'w') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('收益是否已经分配给出资人')" width="180" align="center" prop="distributionLP" :formatter="distributionLPFormat" />
          <el-table-column :label="$t('分摊方式')" align="center" prop="shareWay" :formatter="shareWayFormat" show-overflow-tooltip="true" />
          <el-table-column :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" width="240">
            <template slot-scope="scope">
              <div>
                <el-button
                  size="small"
                  type="text"
                  icon="el-icon-s-order"
                  @click="fundIncomeDetailHandle(scope.row)"
                >{{ $t('基金收益明细') }}</el-button>
                <el-button
                  v-hasPermi="['fund:income:edit']"
                  size="small"
                  type="text"
                  icon="el-icon-edit"
                  @click="updateHandle(scope.row)"
                >{{ $t('修改') }}</el-button>
                <el-button
                  v-hasPermi="['fund:income:remove']"
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  :disabled="scope.row.dealId"
                  @click="deleteHandle(scope.row)"
                >{{ $t('删除') }}</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改基金收益对话框 -->
        <el-dialog :title="title" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
          <fundIncomeForm ref="fundIncomeForm" />
        </el-dialog>
        <!-- 基金收益明细 -->
        <el-dialog :title="title" :visible.sync="listOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
          <fundIncomeDetailList ref="fundIncomeDetailList" />
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  listFundIncome,
  delFundIncome,
  findDealBase,
  getChartList,
  getChartLists,
  getFundIncomeSum
} from '@/api/fund/income/fundIncome'
import fundIncomeForm from './fundIncomeForm.vue'
  import fundIncomeDetailList from '@/views/fund/incomeDetail/fundIncomeDetailList'
import FundLpSelect from '@/components/Select/fundLpSelect'
import CircleChart from '@/views/chart/circleChart'

export default {
    components: {
        fundIncomeForm,
        fundIncomeDetailList,
      FundLpSelect,
      CircleChart
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 总条数
          total: 0,
          // 回款时间
          distributionDates: undefined,
          equityChangeTimes: undefined,
          // 基金收益表格数据
          fundIncomeList: [],
          fundIncomeSum: {},
          // 系统是否
          lpOptions: [],
          // 费用类型
          typeFeeOptions: [],
          shareWayOptions: [],
          // 项目名称
          dealBaseList: [],
          // 弹出层标题
          title: '',
          // 是否显示弹出层
          formOpen: false,
          listOpen: false,
          // 查询参数
          queryParams: {
              fundId: this.$route.query.id,
              dealId: undefined,
              distributionLP: undefined,
              startDate: undefined,
              equityChangeStartDate: undefined,
              equityChangeEndDate: undefined,
              endDate: undefined,
              pageNum: 1,
              pageSize: 10,
              type: 'hk',
            investId: undefined,
            typeFee: undefined
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {},
        tableHeight: 0,
        dataChartList: {},
        dataList: [],
        tLoading: true,
        lLoading: true,
        tableType: 'hk'
      }
  },
  watch: {
    dataList: {
      handler() {
        // this.tLoading = true
        this.$nextTick(() => {
          var tableDiv = document.getElementById('table')
          this.tableHeight = tableDiv.clientHeight - 30
          // this.tLoading = false
        })
      },
      deep: true,
      immediate: true
    }
  },
  created() {
      this.getDicts('sys_yes_no').then(response => {
        this.lpOptions = response.data
      })
    this.getDicts('fund_income_type_fee').then(response => {
      response.data.push({
        dictLabel: '项目收益',
        dictValue: 'XMSY'
      })
      this.typeFeeOptions = response.data
      this.getChartList()
      this.getChartsList()
    })
      this.getList()
      findDealBase(this.$route.query.id).then(response => {
        this.dealBaseList = response.data
      })
      this.getDicts('fund_share_way').then(response => {
        this.shareWayOptions = response.data
      })
  },
  methods: {
    tableStyle({ row, column, rowIndex, columnIndex }) {
      console.log(row, column, rowIndex, columnIndex)
      if (column.property.indexOf('FY-') !== -1) {
        return {
          background: 'rgba(246, 247, 251, 1)'
        }
      }
    },
    radioChange(e) {
      this.queryParams.type = e
      this.getChartsList()
    },
    getChartList() {
      this.lLoading = true
      getChartList(this.queryParams).then(res => {
        var arr = []
        var hasArr = []
        var sum = 0
        res.data.forEach(item => {
          var obj = {}
          obj[item.type] = item.amountMoney
          obj['dictValue'] = item.type
          arr.push(obj)
          hasArr.push(item.type)
          sum += item.amountMoney
        })
        this.typeFeeOptions.forEach(dict => {
          if (!hasArr.includes(dict.dictValue)) {
            var obj = {}
            obj[dict.dictValue] = ''
            obj['dictValue'] = dict.dictValue
            arr.push(obj)
          }
        })
        arr.push({ 'SUM': sum })
        this.expenseSum = sum
        var obj = {}
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].dictValue === 'XMSY') {
            obj = arr[i]
            arr.splice(i, 1)
            break
          }
        }
        var objArr = [obj]
        var newArr = objArr.concat(arr)
        this.dataList = newArr
        this.lLoading = false
      })
    },
    getChartsList() {
      this.tLoading = true
      getChartLists(this.queryParams).then(res => {
        console.log(res)
        this.dataChartList = { columns: [], data: [] }
        this.dataChartList = res.data
        this.tLoading = false
      })
    },
    /** 查询基金收益列表 */
    getList() {
        this.loading = true
        // 回款时间区间查询参数赋值
        if (this.distributionDates != null && this.distributionDates.length > 1) {
          this.queryParams.startDate = this.distributionDates[0]
          this.queryParams.endDate = this.distributionDates[1]
        } else {
          this.queryParams.startDate = undefined
          this.queryParams.endDate = undefined
        }
        // 权益变更时间区间查询参数赋值
        if (this.equityChangeTimes != null && this.equityChangeTimes.length > 1) {
          this.queryParams.equityChangeStartDate = this.equityChangeTimes[0]
          this.queryParams.equityChangeEndDate = this.equityChangeTimes[1]
        } else {
          this.queryParams.equityChangeStartDate = undefined
          this.queryParams.equityChangeEndDate = undefined
        }
        getFundIncomeSum(this.queryParams).then(response => {
          this.fundIncomeSum = response.data
        })
        listFundIncome(this.queryParams).then(response => {
            this.fundIncomeList = response.rows
            this.total = response.total
            this.loading = false
        })
    },
    // 分摊方式 字典翻译
    shareWayFormat(row) {
      return this.selectDictLabel(this.shareWayOptions, row.shareWay)
    },
    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            fundId: undefined,
            dealId: undefined,
            distributionTime: undefined,
            amountPrincipal: undefined,
            amountIncome: undefined,
            amountBonus: undefined,
            amountOthers: undefined,
            amountDistribution: undefined,
            currency: undefined,
            remark: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined,
            investId: undefined,
            typeFee: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
        this.getChartsList()
        this.getChartList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.distributionDates = undefined
        this.equityChangeTimes = undefined
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.title = this.$t('基金收益')
        this.$nextTick(() => {
            this.$refs.fundIncomeForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.title = this.$t('基金收益')
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.fundIncomeForm.init(row)
        })
    },
    /** 基金收益明细 */
    fundIncomeDetailHandle(row) {
      this.listOpen = true
      this.title = this.$t('基金收益明细')
      this.$nextTick(() => {
        // 调用List页面的 fundIncomeDetailList 方法初始化数据
        this.$refs.fundIncomeDetailList.getfundIncomeDetail(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return delFundIncome(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
      this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        this.downLoadExcel('/income/fundIncome/export', this.queryParams)
      }).catch(() => {
      })
    },
    // 是否分给配LP 系统是否字典翻译
    distributionLPFormat(row) {
      return this.selectDictLabel(this.lpOptions, row.distributionLP)
    },
    typeFeeFormat(row) {
      return this.selectDictLabel(this.typeFeeOptions, row.typeFee)
    },
    moneyFormats(money) {
      if (money === 0 || money === '0') {
        return ''
      }
      return this.moneyFormat(money, 'w')
    },
    // 合计
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 4) {
          sums[index] = this.moneyFormat(this.fundIncomeSum.amountPrincipal, 'w')
        } else if (index === 5) {
          sums[index] = this.moneyFormat(this.fundIncomeSum.amountIncome, 'w')
        } else if (index === 6) {
          sums[index] = this.moneyFormat(this.fundIncomeSum.amountBonus, 'w')
        } else if (index === 7) {
          sums[index] = this.moneyFormat(this.fundIncomeSum.amountOthers, 'w')
        } else if (index === 8) {
          sums[index] = this.moneyFormat(this.fundIncomeSum.amountDistribution, 'w')
        } else {
          sums[index] = ''
        }
      })
      return sums
    }
  }
}
</script>
<style lang="scss" scoped>
.table {
  min-height: 120px;
  max-height: 400px;
}
.fund-parent {
  background-color: #F8F9FA;
  height: 48px;
  margin-right: 10px;
  padding:0 5px;
  &:nth-child(2n){
    margin: 0;
  }

  .left-text{
    text-align: left;
    // flex: 1;
    display: flex;
    align-items: center;
    // width: calc(100% - 100px);
  }

  .referenceSpan{
    white-space: nowrap;
    overflow: hidden;
    width: calc(100% - 2vh);
    text-overflow: ellipsis;
    font-size: 13px;
    max-width: 100px;
  }

  .money-text {
    color: rgb(51, 52, 54);
    font-weight: bold;
    padding-left: 10px;
    display: block;
    // max-width: 100px;
    flex: 1;
    font-size: 14px;
    text-align: right;
  }
}

</style>
